from http.server import BaseHTTPRequestHandler, HTTPServer
import cgi
import os
import uuid


class PDFUploadHandler(BaseHTTPRequestHandler):
    # 指定上传目录
    UPLOAD_DIR = "uploads"

    def do_POST(self):
        # 只处理特定路径的POST请求
        if self.path != '/elkhisagent/report/upload':
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'404 Not Found')
            return

        try:
            # 解析multipart/form-data格式
            form = cgi.FieldStorage(
                fp=self.rfile,
                headers=self.headers,
                environ={'REQUEST_METHOD': 'POST'}
            )

            # 检查是否有文件字段
            if 'file' not in form:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'No file uploaded')
                return

            file_item = form['file']

            # 检查是否是文件
            if not file_item.file:
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'No file uploaded')
                return

            # 检查文件类型是否为PDF
            if file_item.filename and not file_item.filename.lower().endswith('.pdf'):
                self.send_response(400)
                self.end_headers()
                self.wfile.write(b'Only PDF files are allowed')
                return

            # 创建上传目录（如果不存在）
            if not os.path.exists(self.UPLOAD_DIR):
                os.makedirs(self.UPLOAD_DIR)

            # 生成唯一文件名
            filename = f"{uuid.uuid4().hex}.pdf"
            filepath = os.path.join(self.UPLOAD_DIR, filename)

            # 保存文件
            with open(filepath, 'wb') as f:
                file_item.file.seek(0)
                f.write(file_item.file.read())

            # 返回成功响应
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            response = {
                'status': 'success',
                'message': 'File uploaded successfully',
                'filename': filename
            }
            self.wfile.write(str(response).encode('utf-8'))

        except Exception as e:
            self.send_response(500)
            self.end_headers()
            self.wfile.write(f'Error: {str(e)}'.encode('utf-8'))


def run_server(port=8000):
    server_address = ('', port)
    httpd = HTTPServer(server_address, PDFUploadHandler)
    print(f'Server running on port {port}...')
    httpd.serve_forever()


if __name__ == '__main__':
    run_server()